package com.atguigu.com.nio.nio_5_零拷贝;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @Author songyahui
 * @Date 2023/10/29 15:13
 * @Description
 */
public class NewIOServer {
    public static void main(String[] args) throws IOException {
        InetSocketAddress address = new InetSocketAddress(8001);
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        ServerSocket serverSocket = serverSocketChannel.socket();
        serverSocket.bind(address);
//        创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(4096);
        while (true){
            SocketChannel socketChannel = serverSocketChannel.accept();
            System.out.println("client info: "+socketChannel.getRemoteAddress().toString());
            int readcount = 0;
            while (readcount >= 0){ //或者readcount != -1 也可
                try{
                    readcount = socketChannel.read(buffer);
                }
                catch (Exception ex){
//                    ex.printStackTrace();
                    break;
                }
//                倒带 position = 0 & mark 作废
                buffer.rewind();

            }
        }
    }
}
